<?php
namespace app\index\controller;

class Order extends Base
{
    public function index(){
        // var_dump(input('get.'));die;
        $user = session('user','','index');
        if(!$user){
            $this->error('请登录','user/login');
        }

        $id = input('get.id',0,'intval');
        if(!$id){
            $this->error('商品ID不合法');
        }
        $dealCount = input('get.deal_count',0,'intval');
        $totalPrice = input('get.total_price');

        $deal = model('Deal')->find($id);
        if(!$deal || $deal->status != 1){
            $this->error('该商品不存在');
        }

        if(empty($_SERVER['HTTP_REFERER'])){
            $this->error('请求不合法');
        }

        //组装入库数据
        $orderSn = setOrderSn();
        $data = [
            'out_trade_no' => $orderSn,
            'user_id' => $user->id,
            'username' => $user->username,
            'deal_id' => $id,
            'deal_count' => $dealCount,
            'total_price' => $totalPrice,
            'referer' => $_SERVER['HTTP_REFERER'],
        ];

        try{
            $orderId = model('Order')->add($data);
        } catch (\Exception $e){
            $this->error('订单处理失败');
        }

        //跳转支付页面
        $this->redirect(url('pay/index',['id' => $orderId]));
    }

    public function confirm()
    {
        $user = session('user','','index');
        if(!$user){
            //点击购买时，若用户没有登陆则跳转登陆页面
            $this->redirect(url('user/login'));
        }

        $id = input('get.id',0,'intval');
        if(!$id){
            $this->error('商品ID不合法');
        }
        $count = input('get.count',1,'intval');

        $deal = model('Deal')->find($id);

        // echo model('Deal')->getLastSql();die;
        if(!$deal || $deal->status != 1){
            $this->error('该商品不存在');
        }



    	return $this->fetch('',[
            'controller' => 'pay',
            'count' => $count,
            'deal' => $deal,
        ]);
    }
}
